import React, { Component } from "react";
import { Text, View, Alert } from "react-native";
import CustomHeader from "../../components/CustomHeader";
import { Input } from "react-native-elements";
import { request } from "../../utils";

export class UpdatePhone extends Component {
  constructor(props) {
    super(props);
    this.state = {
      phone: "",
      phoneError: ""
    };
  }

  submit = _ => {
    const { navigation } = this.props;
    const { phone } = this.state;
    if (!phone) {
      return;
    }

    request(
      "user/updatePhone",
      { phone },
      userInfo => {
        global.userInfo = userInfo;
        navigation.getParam("getUserInfo")();
        navigation.goBack();
      },
      data => Alert.alert(data)
    );
  };

  checkPhone = _ => {
    const { phone } = this.state;
    request(
      "user/checkPhone",
      { phone },
      _ => this.setState({ phoneError: "" }),
      data => this.setState({ phoneError: data })
    );
  };

  render() {
    const { phoneError } = this.state;
    return (
      <View>
        <CustomHeader
          title="设置手机"
          right="check"
          onRightClick={this.submit}
        />

        <Input
          placeholder="手机号码"
          keyboardType="phone-pad"
          errorMessage={phoneError}
          onChangeText={phone => this.setState({ phone }, this.checkPhone)}
        />
      </View>
    );
  }
}

export default UpdatePhone;
